package com.youdianda.service.impl;

import com.youdianda.constant.ConfigFgxConstant;
import com.youdianda.constant.MenuTypeFgxConstant;
import com.youdianda.constant.MessageConstant;
import com.youdianda.constant.StatusConstant;
import com.youdianda.context.BaseContext;
import com.youdianda.dto.LoginDTO;
import com.youdianda.entity.*;
import com.youdianda.exception.AccountLockedException;
import com.youdianda.exception.AccountNotFoundException;
import com.youdianda.exception.PasswordErrorException;
import com.youdianda.mapper.SysIndexFgxMapper;
import com.youdianda.result.Result;
import com.youdianda.service.SysIndexFgxService;
import com.youdianda.util.JwtUtil;
import com.youdianda.vo.BaseInfoFgxVO;
import com.youdianda.vo.ProfileFgxVO;
import com.youdianda.vo.SysConfigFgxVO;
import com.youdianda.vo.UserFgxVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysIndexFgxServiceImpl implements SysIndexFgxService {

    @Autowired
    private SysIndexFgxMapper indexMapper;

    /**
     * 获取系统配置
     * @return
     */
    @Transactional
    @Override
    public Result getConfig() {
        List<SysConfig> configList = indexMapper.getConfig(ConfigFgxConstant.SYSTEM);
        SysConfigFgxVO configVO = new SysConfigFgxVO();
        if (configList != null && configList.size() > 0){
            configList.forEach(sysConfig -> {
                switch (sysConfig.getAttr_key()){
                    case ConfigFgxConstant.LOGIN_TITLE:
                        configVO.setLogin_title(sysConfig.getAttr_value());
                        break;
                    case ConfigFgxConstant.LOGIN_BG:
                        configVO.setSystem_logo(sysConfig.getAttr_value());
                        break;
                    case ConfigFgxConstant.SYSTEM_NAME:
                        configVO.setSystem_name(sysConfig.getAttr_value());
                        break;
                    case ConfigFgxConstant.SYSTEM_LOGO:
                        configVO.setLogin_bg(sysConfig.getAttr_value());
                        break;
                    case ConfigFgxConstant.WEB_ICO:
                        configVO.setWeb_ico(sysConfig.getAttr_value());
                        break;
                    default:
                        break;
                }
            });
        }
        return Result.success(configVO);
    }

    /**
     * 登录接口
     * @return
     */
    @Transactional
    @Override
    public Result login(LoginDTO dto) {
        String username = dto.getLogin_name();
        String password = dto.getPassword();

        //1、根据用户名查询数据库中的数据
        SysFgxUser sysUser = indexMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (sysUser == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //对用户输入的明文密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(sysUser.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (sysUser.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //直接用ID生成token
        String token = JwtUtil.getToken(Long.valueOf(sysUser.getId()));
        Map map = new HashMap();
        map.put("token",token);

        return Result.success(map);
    }

    /**
     * 获取用户资料
     * @return
     * userInfo
     * menuList
     * dictsList
     * btnList 用户按钮权限
     */
    @Transactional
    @Override
    public Result profile() {
        SysFgxUser sysUser = indexMapper.userInfo(BaseContext.getCurrentId());
        List<SysFgxMenu> menuList = indexMapper.menuList(MenuTypeFgxConstant.Menu);

        List<SysFgxDict> interface_types = indexMapper.dictsList(ConfigFgxConstant.INTERFACE_TYPE);
        List<SysFgxDict> order_types = indexMapper.dictsList(ConfigFgxConstant.ORDER_TYPE);
        List<SysFgxDict> table_types = indexMapper.dictsList(ConfigFgxConstant.TABLE_TYPE);
        List<SysFgxDict> report_types = indexMapper.dictsList(ConfigFgxConstant.REPORT_TYPE);
        List<SysFgxDict> themes = indexMapper.dictsList(ConfigFgxConstant.THEME);
        Map map = new HashMap();
        if (interface_types != null && interface_types.size() > 0){
            Map interface_typesMap = new HashMap();
            interface_types.forEach(sysDict -> {
                interface_typesMap.put(sysDict.getValue(), sysDict.getLabel());
            });
            map.put(ConfigFgxConstant.INTERFACE_TYPE, interface_typesMap);
        }

        if (order_types != null && order_types.size() > 0){
            Map order_typesMap = new HashMap();
            order_types.forEach(sysDict -> {
                order_typesMap.put(sysDict.getValue(), sysDict.getLabel());
            });
            map.put(ConfigFgxConstant.ORDER_TYPE, order_typesMap);
        }

        if (table_types != null && table_types.size() > 0){
            Map table_typesMap = new HashMap();
            table_types.forEach(sysDict -> {
                table_typesMap.put(sysDict.getValue(), sysDict.getLabel());
            });
            map.put(ConfigFgxConstant.TABLE_TYPE, table_typesMap);
        }

        if (report_types != null && report_types.size() > 0){
            Map report_typesMap = new HashMap();
            report_types.forEach(sysDict -> {
                report_typesMap.put(sysDict.getValue(), sysDict.getLabel());
            });
            map.put(ConfigFgxConstant.REPORT_TYPE, report_typesMap);
        }

        if (themes != null && themes.size() > 0){
            Map themesMap = new HashMap();
            themes.forEach(sysDict -> {
                themesMap.put(sysDict.getValue(), sysDict.getLabel());
            });
            map.put(ConfigFgxConstant.THEME, themesMap);
        }

        ArrayList arrayList = new ArrayList();
        arrayList.add("*");
        ProfileFgxVO profileVO = new ProfileFgxVO();
        profileVO.setUserInfo(sysUser);
        profileVO.setMenuList(menuList);
        profileVO.setDictsList(map);
        profileVO.setBtnList(arrayList);

        return Result.success(profileVO);
    }

    @Transactional
    @Override
    public Result baseInfo() {
        BaseInfoFgxVO baseInfoVO = new BaseInfoFgxVO();
        List<YddFgxCate> cateList = indexMapper.allcate();
        cateList.forEach(yddCate -> yddCate.setNum(yddCate.getSort_num()));
        List<YddUser> newUserList = indexMapper.newUser();
        List<YddArticle> articleList = indexMapper.hotArticle(1);
        Integer sum = indexMapper.userSum();
        Integer manSum = indexMapper.userSexSum(1);
        Integer womanSum = indexMapper.userSexSum(0);
        Integer advposNum = indexMapper.advposNum();
        Integer advimgNum = indexMapper.advimgNum();
        Integer articleNum = indexMapper.articleNum();
        Integer tagNum = indexMapper.tagNum();
        Integer adminNum = indexMapper.adminNum();
        UserFgxVO userVO = new UserFgxVO();
        userVO.setTotal(sum);
        userVO.setUser_man(manSum);
        userVO.setUser_woman(womanSum);
        baseInfoVO.setUser(userVO);
        baseInfoVO.setAdvpos_num(advposNum);
        baseInfoVO.setTag_num(tagNum);
        baseInfoVO.setAdmin_num(adminNum);
        baseInfoVO.setArticle_num(articleNum);
        baseInfoVO.setCate_num(cateList.size());
        baseInfoVO.setAdvimg_num(advimgNum);

        baseInfoVO.setNew_user(newUserList);
        baseInfoVO.setAll_cate(cateList);
        baseInfoVO.setHot_article(articleList);
        return Result.success(baseInfoVO);
    }
}
